# coding: utf8

from math import sqrt
from numpy import mean, matmul, eye
from scipy import optimize as opt


def extract_rotation(source_cloud, target_cloud):
    """ Extract rotation using powell method.
    :param source_cloud: the source cloud.
    :param target_cloud: the target cloud.
    :return: the rotation matrix.
    """
    rs = opt.fmin_powell(
            lambda r: mean([sqrt(pow(matmul(r.reshape(3,3), s) - t, 2).sum()) for s, t in zip(source_cloud, target_cloud)]),
            eye(3)
    )
    return rs.reshape(3, 3)